﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSocketSharp.Server;
using WebSocketSharp;
using PServiceBus.Core.Manager;

namespace PServiceBus.SharpWebSocket {
    public class SharpWebSocketService : WebSocketService, PServiceBus.Core.Interface.IWebSocketConnection {

        protected override void OnOpen(object sender, EventArgs e) {
            WebSocketConnectionManager.Register(this);
        }

        protected override void OnMessage(object sender, MessageEventArgs e) {
            if (SharpWebSocketServer.Current.OnMessage == null) return;
            SharpWebSocketServer.Current.OnMessage(this, e.Data);
        }

        protected override void OnError(object sender, ErrorEventArgs e) {
            if (SharpWebSocketServer.Current.OnError == null) return;
            SharpWebSocketServer.Current.OnError(this, new Exception(e.Message));            
        }

        protected override void OnClose(object sender, CloseEventArgs e) {
            WebSocketConnectionManager.UnRegister(this);
            if (SharpWebSocketServer.Current.OnClose == null) return;
            SharpWebSocketServer.Current.OnClose(this);
        }

        #region IWebSocketConnection Members

        void Core.Interface.IWebSocketConnection.Send(string message) {
            Send(message);
        }

        void Core.Interface.IWebSocketConnection.Close() {
            Stop();
        }

        private Guid? _id;
        Guid Core.Interface.IWebSocketConnection.ID {
            get {
                return _id ?? (_id = Guid.Parse(ID)) ?? Guid.Empty;
            }
            set {
                _id = value;
            }
        }

        #endregion

        #region IWebSocketConnection Members


        public string ClientIpAddress { get; set; }

        #endregion
    }
}
